﻿using System.Windows.Browser;
using System.Windows.Controls;
using System;
using System.Windows;

namespace SuperGo.Silverlight {
	public abstract class ControlBase : UserControl {
		Panel _rootPanel;
		Page _page;

		public ControlBase() {
			
		}

		public Page Page {
			get {
				// cache the page, since GetPage is somewhat expensive
				if (_page == null)
					_page = GetPage();
				return _page;
			}
		}

		public Panel RootPanel {
			get {
				// cache the root panel
				if (_rootPanel == null)
					_rootPanel = GetRootPanel();
				return _rootPanel; 
			}
		}

		private Panel GetRootPanel() {
			object layoutRoot = FindName("LayoutRoot");
			Panel panelRoot = layoutRoot as Panel;
			if (panelRoot == null)
				throw new Exception("Expected a root named LayoutRoot");
			return panelRoot;
		}

		private Page GetPage() {
			FrameworkElement rootParent = RootPanel.Parent as FrameworkElement;
			return GetPage(rootParent);
		}

		public static Page GetPage(FrameworkElement anyElement) {
			while (!typeof(Page).IsAssignableFrom(anyElement.GetType())) {
				anyElement = anyElement.Parent as FrameworkElement;
				if (anyElement == null)
					throw new Exception("Some control somewhere does not inherit from ControlPageBase.");
			}
			
			return (Page)anyElement;
		}

		public void HandleException(Exception ex) {
			Dispatcher.BeginInvoke(() => HtmlPage.Window.Alert(ex.ToString()));
			//throw ex;
			//Page.ShowDialog("An Error Occurred", "The following error occurred: " + ex);
		}
	}
}
